# 导入相关库和模块
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import SessionLocal
import sys
from admin.base_controller import BaseController
from config.logging import logger
from services.admin.user_role_api_service import UserRoleApiService


# 定义获取数据库会话的依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义控制器类
class UserRoleApi(BaseController):
    def __init__(self):
        super().__init__()
        self.router = APIRouter()

    async def list_user_roles(self, db: Session = Depends(get_db), name: str = Query(None),
                              page: int = Query(default=1, ge=1), limit: int = Query(default=20, ge=1)):
        """
        角色列表
        :param db:
        :param name:
        :param page:
        :param limit:
        :return:
        """
        service = UserRoleApiService(db)
        lists = await service.list_user_roles(page, limit, name)
        return self.success_response(data=lists, message="success")

    async def detail_user_role(self, role_id: int, db: Session = Depends(get_db)):
        """
        角色详情
        :param role_id:
        :param db:
        :return:
        """
        service = UserRoleApiService(db)
        result = await service.detail_user_role(role_id)
        return self.success_response(data=result, message="success")

    async def create_user_role(self, data: dict, db: Session = Depends(get_db)):
        """
        创建角色
        :return:
        """
        service = UserRoleApiService(db)
        result = await service.create_user_role(data)
        return self.success_response(data=result, message="角色添加成功")

    async def update_user_role(self, data: dict, role_id: int, db: Session = Depends(get_db)):
        """
        编辑角色
        :param name:
        :param desc:
        :param role_id:
        :param db:
        :return:
        """
        service = UserRoleApiService(db)
        result = await service.update_user_role(data, role_id)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="角色编辑成功")

    async def delete_user_role(self, ids: int, db: Session = Depends(get_db)):
        """
        删除角色
        :param ids:
        :param db:
        :return:
        """
        service = UserRoleApiService(db)
        result = await service.delete_user_role(ids)
        return self.success_response(data=result, message="角色编辑成功")

    async def assign_permissions_to_role(self, permissionData: dict,
                                         db: Session = Depends(get_db)):
        # 授权权限给角色
        service = UserRoleApiService(db)
        result = await service.assign_permissions_to_role(permissionData)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="权限绑定成功")

    async def assign_user_to_role(self, data: dict, db: Session = Depends(get_db)):
        """
        用户绑定角色
        data: {"user_id": 1, "role_id":1}
        """
        service = UserRoleApiService(db)
        result = await service.assign_user_to_roles(data)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")



# 使用
user_role_api = UserRoleApi()
router = user_role_api.router
